import storage from "./storage";
import {stringify} from 'qs'
import utils from './utils.js'

let clientId;
let defaultRules;

/**
 * 获取api地址及认证
 * @return {Promise<{url: *}|{authorization: string, url: string}>}
 */
const apiUrl = async () => {
  const url = (await storage.getApiUrl())?.replace(/\/$/, '')
  if (!url) return {url}
  const {origin, username, password} = new URL(url)
  if (username || password) {
    return {
      url: origin,
      authorization: 'Basic ' + btoa(`${username}:${password}`)
    }
  }
  return {
    url: origin
  }
};
export default {
  async getInitInfo() {
    const {url, authorization} = await apiUrl()
    const res = await fetch(`${url}/cgi-bin/init?_=${new Date().getTime()}`, {headers: {authorization}})
    const data = await res.json()
    clientId = data.clientId;
    defaultRules = data.rules.defaultRules;
    let rulesActive = data.rules.list?.filter(item => item.selected)?.length ?? 0
    if (!data.rules.defaultRulesIsDisabled) {
      rulesActive++
    }
    utils.setBadge(rulesActive)
    return data;
  },
  async setRuleEnable(item, isEnable) {
    const {url, authorization} = await apiUrl()
    return await fetch(isEnable ? `${url}/cgi-bin/rules/select` : `${url}/cgi-bin/rules/unselect`, {
      method: 'post', headers: {
        Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded',
        authorization
      }, body: stringify({
        clientId,
        name: item.name,
        value: item.data,
        selected: true,
        active: true,
        key: `w-reactkey-${item.index + 2}`,
        icon: 'checkbox',
        hide: false,
        changed: false
      })
    })
  },
  async changeDefaultRule(isEnable) {
    const {url, authorization} = await apiUrl()
    return await fetch(isEnable ? `${url}/cgi-bin/rules/enable-default` : `${url}/cgi-bin/rules/disable-default`, {
      method: 'post', headers: {
        Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded',
        authorization
      }, body: stringify({
        clientId,
        name: 'Default',
        fixed: true,
        value: defaultRules,
        selected: true,
        isDefault: true,
        active: true,
        key: 'w-reactkey-1',
        icon: 'checkbox'
      })
    })
  },
  async setAllowMultipleChoice(isAllow) {
    const {url, authorization} = await apiUrl()
    return await fetch(`${url}/cgi-bin/rules/allow-multiple-choice`, {
      method: 'post', headers: {
        Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded',
        authorization
      }, body: stringify({
        clientId, allowMultipleChoice: isAllow ? 1 : 0
      })
    })
  }
}
